package org.stvd.controller.admin;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.stvd.common.Consts;
import org.stvd.common.aspectj.lang.annotation.Log;
import org.stvd.common.aspectj.lang.enums.BusinessType;
import org.stvd.common.security.SecurityUserHolder;
import org.stvd.common.utils.InterfaceResult;
import org.stvd.controller.BaseController;
import org.stvd.core.util.StringUtil;
import org.stvd.entities.admin.Guids;
import org.stvd.entities.admin.Menus;
import org.stvd.entities.admin.TreeNode;
import org.stvd.service.admin.GuidsService;
import org.stvd.service.admin.MenusService;
import org.stvd.service.common.CommonService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

/**
 * @Title: MenusController
 * @Description: 系统菜单控制类
 * @author houzx
 * @date 2020年8月8日
 */
@Api(tags = "系统菜单接口类")
@Controller
@RequestMapping("/admin/menus")
public class MenusController extends BaseController {

    @Autowired
    private MenusService menusService;
    @Autowired
    private GuidsService guidsService;
    @Autowired
    private CommonService commonService;
    
    @Value("${top_guid}")
    private String topGuid = "";
    
    private String tmpURL = "/admin/menus/";

    /**
     * 系统菜单管理
     * @return
     */
    @ApiIgnore
    @GetMapping(value = "management")
    public String onPageLoad(@ModelAttribute("menus") Menus menus) {
        if(!StringUtil.isEmpty(request.getParameter("gid"))) {
            menus.setGuid(request.getParameter("gid"));
        }
        if(StringUtil.isEmpty(menus.getGuid())) {
            menus.setGuid(StringUtil.isEmpty(topGuid) ? Consts.GUID :topGuid);
        }
        loadMenuResource(menus);
        return tmpURL + "MenusManagement.html";
    }
    
    @ApiIgnore
    @PostMapping(value = "management")
    public String onPageAction(@ModelAttribute("menus") Menus menus) {
        loadMenuResource(menus);
        return tmpURL + "MenusManagement.html";
    }
    
    // 加载菜单资源信息公共方法
    private void loadMenuResource(Menus menus) {
        String userId = SecurityUserHolder.getCurrentUserId();
        map.put("guidsList", guidsService.listGuidByUserId(userId));
        map.put("menuList", queryMenusByGuid(menus.getGuid()));
        map.put("guids", guidsService.findByPk(Guids.class, StringUtil.isEmpty(topGuid) ? Consts.GUID :topGuid));
    }
    
    /**
     * 系统菜单新增请求
     * @param guid
     * @param menus
     * @return
     */
    @ApiIgnore
    @GetMapping(value = "add/{guid}")
    public String onAddLoad(@PathVariable String guid, @ModelAttribute("menus") Menus menus) {
        map.put("parentMenus",  queryMenusByGuid(guid));
        map.put("guid", guid);
        return tmpURL + "MenusAdd.html";
    }
    
    @ApiOperation(value = "新增菜单信息")
    @Log(title = "新增菜单信息", businessType = BusinessType.INSERT)
    @PostMapping(value = "add")
    @ResponseBody
    public InterfaceResult<Map<String, Object>> onMenuAddAction(
        @Valid @ModelAttribute("menus") Menus menus, BindingResult bindingResult){
        InterfaceResult<Map<String, Object>> result = new InterfaceResult<Map<String,Object>>();
        if (bindingResult.hasErrors()) {
            result.setError(bindingResult.getAllErrors().get(0).getDefaultMessage());
            return result;
        }
        menus.setMenuId(StringUtil.getRandomUUID());
        menusService.insertMenu(menus);
        result.setMsg("新增成功！");
        return result;
    }

    /**
     * 系统菜单修改请求
     * @param menuId 菜单ID
     * @return
     */
    @ApiIgnore
    @GetMapping(value = "edit/{mid}")
    public String onEditLoad(@PathVariable String mid,
        @ModelAttribute("menus") Menus menus) {
        menus = menusService.findByPk(Menus.class, mid);
        if(menus!=null) {
            map.put("menus", menus);
            map.put("oldUpperId", menus.getUpperId());
            map.put("parentMenus", queryMenusByGuid(menus.getGuid()));
        }
        return tmpURL + "MenusEdit.html";
    }
    
    @ApiOperation(value = "修改菜单信息")
    @Log(title = "修改菜单信息", businessType = BusinessType.UPDATE)
    @PostMapping(value = "edit")
    @ResponseBody
    public InterfaceResult<Map<String, Object>> onEditAction(
        @Valid @ModelAttribute("menus") Menus menus, BindingResult bindingResult) {
        InterfaceResult<Map<String, Object>> result = new InterfaceResult<Map<String,Object>>();
        if (bindingResult.hasErrors()) {
            result.setError(bindingResult.getAllErrors().get(0).getDefaultMessage());
            return result;
        }
        if (menus.getMenuId().equals(menus.getUpperId())
                || menusService.isChildMenu(menus.getGuid(), menus.getMenuId(), menus.getUpperId())) {
            result.setError("上级菜单不能是子菜单！");
            return result;
        }
        String oldUpperId = request.getParameter("oldUpperId");
        menusService.updateMenu(menus, oldUpperId);
        map.clear();
        result.setMsg("修改成功！");
        return result;
    }

    /**
     * 删除菜单
     * @param menuId 菜单ID
     * @return
     */
    @ApiOperation(value = "删除菜单信息")
    @Log(title = "删除菜单信息", businessType = BusinessType.DELETE)
    @PostMapping(value = "del")
    @ResponseBody
    public InterfaceResult<Map<String, Object>> onDelete(String menuId) {
        InterfaceResult<Map<String, Object>> result = new InterfaceResult<Map<String,Object>>();
        try {
            Menus menu = menusService.findByPk(Menus.class, menuId);
            if (menusService.findByParentID(menu.getGuid(), menu.getMenuId()).size() > 0) {
                result.setError("菜单‘" + menu.getMenuCaption() + "’不能删除！存在子菜单！");
            } else {
                menusService.deleteMenu(menu);
                result.setMsg("菜单‘" + menu.getMenuCaption() + "’删除成功！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setError("删除菜单失败！<br/>失败原因：" + e.getMessage());
        }
        return result;
    }
    
    /**
     * 使用treegrid的注意事项： 生成的json对象中必须包含state属性值为“closed”/“open”, closed：表示有子节点。
     * open：表示没有子节点。
     */
    @ApiOperation(value = "获取菜单列表")
    @GetMapping(value = "query")
    @ResponseBody
    public List<Menus> onQuery(HttpServletRequest request, ModelMap map, String id) {
        String tmpID = "-1";
        if (id != null) {
            tmpID = id;
        }
        return menusService.findByParentID(StringUtil.isEmpty(topGuid) ? Consts.GUID :topGuid, tmpID);
    }

    /**
     * 获取菜单树列表
     * @param id
     * @return
     */
    @ApiOperation(value = "获取菜单树列表")
    @GetMapping(value = "menustate")
    @ResponseBody
    public List<TreeNode> menuState(String id) {
        String tmpID = "-1";
        List<TreeNode> result = new ArrayList<TreeNode>();
        if (id != null) {
            tmpID = id;
        } else {
            TreeNode defaultMenu = new TreeNode();
            defaultMenu.setId("-1");
            defaultMenu.setText("无上级菜单");
            result.add(defaultMenu);
        }
        List<Menus> list = menusService.findByParentID(StringUtil.isEmpty(topGuid) ? Consts.GUID :topGuid, tmpID);
        for (Menus menu : list) {
            TreeNode tree = new TreeNode();
            tree.setId(menu.getMenuId());
            tree.setText(menu.getMenuCaption());
            tree.setIconCls(menu.getIcon());
            tree.setChildren(menuState(menu.getMenuId()));
            result.add(tree);
        }
        return result;
    }
    
    /**
     * 根据平台ID获取菜单列表
     * @param guid GUID
     * @return 如果当前用户为管理员（拥有ROLE_ADMIN角色），返回所有菜单；如果当前用户不是管理员，返回当前用户权限菜单列表
     */
    public List<Menus> queryMenusByGuid(String guid) {
        String userId = SecurityUserHolder.getCurrentUserId();
        boolean isManage = commonService.checkManage(userId, guid);
        if(isManage) {
            return menusService.findAll(guid);
        }else{
            return menusService.findByUid(userId, guid);
        }
    }
    
}
